<template>
  <div class="flex-container">
    <div class="btngroup" v-if="state.btngroup">
      <el-button type="primary" @click="adduser">邀请人员</el-button>
      <el-button type="primary" @click="opendev">添加视频</el-button>
      <el-button type="primary" @click="opendevv">添加录像</el-button>
      <el-button type="danger" @click="endmeeting">结束会议</el-button>
    </div>
    <div
      :style="
        state.btngroup
          ? 'height:calc(100vh - 135px)'
          : 'height:calc(100vh - 80px)'
      "
      id="mymeet"
    ></div>
    <div class="fv" v-show="state.showv">
      <div
        id="play_window_meet"
        :class="state.islarge == 0 ? 'video1' : 'video2'"
      ></div>
      <div class="vbtn" @click="resize">
        <el-icon size="24" v-if="state.islarge == 0">
          <CirclePlusFilled />
        </el-icon>
        <el-icon size="24" v-if="state.islarge == 1">
          <RemoveFilled />
        </el-icon>
      </div>
    </div>
    <!-- 添加视频 -->
    <devs :isShow="state.visible" @ok="devback" />
    <!-- 添加录像 -->
    <devv :isShow="state.visible2" @ok="devvback" />
    <kmeet
      :show="state.dialog"
      :isk="3"
      :pps="state.people"
      :meet="state.meet"
    />
  </div>
</template>

<script setup ts>
import { ElMessage } from "element-plus";
import devs from "./devs.vue";
import devv from "./devv.vue";
import kmeet from "./kmeet.vue";
import { useMyStore } from "@/pinia/store";
import { useRouter } from "vue-router";
import { format } from "date-fns";
const router = useRouter();
import { getcameraurl } from "@/api/videoplan.js";
import {
  getpeoplelist,
  getgrouplist,
  getchangeGroup,
  getplaybackcameraurl,
} from "@/api/videoMeet.js";

const state = reactive({
  api: null,
  meet: {
    meetingId: "", //会议id
  },
  people: [],
  dialog: false,
  btngroup: false, //是否主持人
  showv: false,
  visible: false,
  visible2: false,
  cameraUrl: "", //视频地址
  pms: {},
  myPlugin: null,
  curIndex: 0, //视频窗口索引
  islarge: 0, //视频窗口缩放
  meid: "", //jitsi id
});
//如果开始显示视频，先初始化
watch(
  () => state.showv,
  (newval) => {
    if (newval == true) {
      initPlayer();
    }
  }
);

const adduser = () => {
  state.dialog = false;
  setTimeout(() => {
    state.dialog = true;
  }, 300);
};

const clostMeet = async () => {
  let data = {
    optType: "C",
    meetingGroupId: state.meet.meetingGroupId,
  };
  try {
    const response = await getchangeGroup(data);
  } catch (error) {
    console.error("操作失败:", error);
  }
};
const startMeet = async () => {
  let data = {
    optType: "S",
    meetingGroupId: state.meet.meetingGroupId,
  };
  try {
    const res = await getchangeGroup(data);
    state.meet.meetingId = res.data.meetingInfo.meetingId;
  } catch (error) {
    console.error("操作失败:", error);
  }
};
const endmeeting = () => {
  router.push("/videoMeet");
};

const resize = () => {
  if (state.islarge == 0) {
    state.islarge = 1;
  } else {
    state.islarge = 0;
  }
  if (state.myPlugin) {
    state.myPlugin.JS_Resize();
  }
};
const play = (pm) => {
  if (state.cameraUrl != "") {
    state.myPlugin.JS_StopRealPlayAll();
    if (pm) {
      state.myPlugin.JS_Play(
        state.cameraUrl,
        { playURL: state.cameraUrl, mode: 1 },
        state.curIndex,
        pm.beginTime,
        pm.endTime
      );
    } else {
      state.myPlugin.JS_Play(
        state.cameraUrl,
        { playURL: state.cameraUrl, mode: 0 },
        state.curIndex
      );
    }

    state.myPlugin.JS_Resize();
  }
};
const initPlayer = () => {
  if (state.myPlugin != null) return;
  state.myPlugin = new JSPlugin({
    szId: "play_window_meet", //需要英文字母开头，唯一性，必填
    szBasePath: "/js/", // 必填,与h5player.min.js的引用目录一致
    bSupporDoubleClickFull: true, //是否支持双击全屏，默认true
    iMaxSplit: 1,
    iCurrentSplit: 1,
  });

  state.myPlugin.JS_SetWindowControlCallback({
    windowEventSelect: function (index) {
      state.curIndex = index;
    },
    pluginErrorHandler: function (iWndIndex, iErrorCode, oError) {
      ElMessage.error(`播放失败, 错误码: ${iErrorCode}`);
    },
  });
};
const destoryPlayer = () => {
  if (state.myPlugin) {
    state.myPlugin.JS_StopRealPlayAll();
    state.myPlugin.JS_DestroyWorker();
    state.myPlugin = null;
  }
};

const opendev = () => {
  state.visible = false;
  setTimeout(() => {
    state.visible = true;
  }, 300);
};
const devback = async (vid, sts) => {
  let { data } = await getcameraurl({
    deviceIds: [vid],
  });
  let urls = data.cameraUrls || [];
  if (urls.length > 0) {
    state.showv = true;
    state.cameraUrl = urls[0].cameraUrl;
    setTimeout(() => {
      state.pms = {};
      play();
      if (state.btngroup && state.cameraUrl != "") {
        let obj = { cameraUrl: state.cameraUrl, pms: state.pms };
        state.api.executeCommand(
          "sendEndpointTextMessage",
          "",
          JSON.stringify(obj)
        );
      }
    }, 300);
  } else {
    state.showv = false;
    ElMessage.error("未获取到播放地址");
  }
};

const opendevv = () => {
  state.visible2 = false;
  setTimeout(() => {
    state.visible2 = true;
  }, 300);
};
const dateFormat = (date, fmt) => {
  return format(new Date(date), fmt);
};
const devvback = async (pm) => {
  const beginTime = dateFormat(pm.dts[0], "yyyy-MM-dd HH:mm:ss");
  const endTime = dateFormat(pm.dts[1], "yyyy-MM-dd HH:mm:ss");

  let params = {
    cameraId: pm.cameraId,
    beginTime: beginTime,
    endTime: endTime,
    uuid: "",
  };
  console.log("params", params);
  let res = await getplaybackcameraurl(params);
  let url = res.data.url || [];
  if (url && url.length > 0) {
    state.showv = true;
    state.cameraUrl = url;
    setTimeout(() => {
      state.pms = params;
      play(params);
      if (state.btngroup && state.cameraUrl != "") {
        let obj = { cameraUrl: state.cameraUrl, pms: state.pms };
        state.api.executeCommand(
          "sendEndpointTextMessage",
          "",
          JSON.stringify(obj)
        );
      }
    }, 300);
  } else {
    state.showv = false;
    ElMessage.error("暂无视频数据");
  }
};

//注销时 销毁组件
onBeforeUnmount(() => {
  destoryPlayer();
  if (state.api) {
    state.api.dispose();
    //如果是主持人离开，同时关闭会议
    if (state.btngroup) {
      clostMeet();
    }
  }
});

onMounted(() => {
  console.log("mounted", state.meet);
  console.log("mounted22222", state.meet.creator);
  let store = useMyStore();
  state.meet = store.params.meet;
  state.people = store.params.people;
  // const domain = import.meta.env.VITE_CASE_DOOR
  // const cleanDomain = domain.replace(/^https?:\/\//, "");
  // const domain = "zxz.linghang.tech:28443";//测试
  const domain = "np.bcdtech.cn:8443";

  const options = {
    roomName: state.meet.meetingTheme, //meet name for update
    parentNode: document.querySelector("#mymeet"),
    lang: "zhCN",
    userInfo: {
      displayName: localStorage.getItem("displayName"), // 取当前登录的名字
    },
  };
  state.api = new JitsiMeetExternalAPI(domain, options);
  console.log("state.api", state.api);

  // 当前用户加入会议的事件
  state.api.addListener("videoConferenceJoined", (event) => {
    console.log("这个用户已加入会议", event);
    const { roomName, id, displayName, avatarURL, breakoutRoom } = event;
    state.meid = id;
    state.api.getRoomsInfo().then((res) => {
      let rooms = res.rooms;
      let len = roomName.length;
      let room = rooms.find((x) => x.id.substring(0, len) == roomName);
      if (room) {
        let ps = room.participants;
        let po = ps.find((x) => x.id == id);
        if (po) {
          if (po.role == "moderator") {
            state.btngroup = true;
            //标记开始
            if (state.meet.stateCode == "0") {
              startMeet();
            }
          }
        }
      }

      //检查用户是否非创建者成为主持人
      if (
        "" + state.meet.creator != localStorage.getItem("userId") &&
        state.btngroup
      ) {
        ElMessage.error("主持人尚未进入，请等待...");
        state.btngroup = false; //强制为非主持人，防止退出时关闭会议
        router.push("/videoMeet");
      }
    });
  });

  //收到消息
  state.api.addListener("participantJoined", (peo) => {
    //如果是主持人，检查视频地址和视频时间，发送给进入者
    console.log("peo", peo);
    if (state.btngroup && state.cameraUrl != "") {
      let obj = { cameraUrl: state.cameraUrl, pms: state.pms };
      state.api.executeCommand(
        "sendEndpointTextMessage",
        peo.id,
        JSON.stringify(obj)
      );
    }
  });

  //收到消息
  state.api.addListener("endpointTextMessageReceived", (ent) => {
    console.log(ent);
    let obj = JSON.parse(ent.data.eventData.text);
    if (obj.cameraUrl != "") {
      state.showv = true;
      state.cameraUrl = obj.cameraUrl;
      setTimeout(() => {
        if (obj.pms.beginTime) {
          play(obj.pms);
        } else {
          play();
        }
      }, 300);
    } else {
      destoryPlayer();
      state.showv = false;
    }
  });

  //当前用户离开
  state.api.addListener("videoConferenceLeft", (ent) => {
    router.push("/videoMeet");
  });
});
</script>

<style lang="scss" scoped>
.flex-container {
  display: flex;
  flex-direction: column;
  position: relative;
}
.btngroup {
  padding: 10px 10px 0 0;
  height: 50px;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-content: center;
}
.fv {
  position: absolute;
  left: 10px;
  top: 10px;
  height: auto;
  width: auto;
  .video1 {
    position: relative;
    height: 200px !important;
    width: 320px !important;
    background: burlywood;
  }
  .video2 {
    position: relative;
    height: 800px !important;
    width: 1280px !important;
    background: burlywood;
  }
}

.vbtn {
  display: none;
  position: absolute;
  right: 10px;
  bottom: 5px;
}
.fv:hover .vbtn {
  display: block;
  cursor: pointer;
}

.dialogSt {
  .tit {
    font-weight: 600;
    font-size: 14px;
    color: #293555;
    line-height: 20px;
  }
}
</style>